import { defineStore } from 'pinia';
import useUserStore from '@/store/modules/user';
import { getMessageByPageAndName } from '@/api/modules/rbac/dcp/message_management';

export const useStatisticalStore = defineStore('statistical', () => {
  const userStore = useUserStore();
  const userId = ref<string>('');
  const account = ref<string>('');
  const condition = ref<string>('');
  const allMsg = ref<any[]>([]);
  const total = ref<number>(0);
  const current = ref<number>(1);
  const pageSize = ref<number>(100);
  const sum = ref<number>(0);
  const successMsg = ref<number>(0);
  const errorMsg = ref<number>(0);
  const getSumMsg = () => {
    successMsg.value = 0;
    errorMsg.value = 0;
    sum.value = allMsg.value.length;
    allMsg.value.forEach((item: any) => {
      if (item.state === '发送成功') {
        successMsg.value++;
      }
      else {
        errorMsg.value++;
      }
    });
  };
  // 辅助函数：将日期字符串转换为Date对象
  function parseDateString(date: any) {
    const dateObject = new Date(date);
    const year = dateObject.getFullYear();
    const month = String(dateObject.getMonth() + 1).padStart(2, '0');
    const day = String(dateObject.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  }

  // 辅助函数：获取当前日期和时间的Date对象（可设置为0时0分0秒以比较日期）
  function getCurrentDate() {
    const now = new Date();
    now.setHours(0, 0, 0, 0); // 设置为当日0点
    return now;
  }

  // 辅助函数：计算指定天数前的日期
  function getDateNDaysAgo(days: number) {
    const now = new Date();
    now.setDate(now.getDate() - days);
    now.setHours(0, 0, 0, 0); // 设置为0点以比较日期
    return now;
  }

  // 辅助函数：计算给定日期范围的起始和结束日期
  function getDateRange(startDateString: string, endDateString: string) {
    const startDate = new Date(startDateString.replace(/-/g, '/')); // 处理日期格式，假设是YYYY-MM-DD
    const endDate = new Date(endDateString.replace(/-/g, '/')); // 处理日期格式，假设是YYYY-MM-DD
    startDate.setHours(0, 0, 0, 0); // 设置为0点
    const endDateNextDay = new Date(endDate);
    endDateNextDay.setDate(endDate.getDate() + 1); // 下一天的0点，用于包含结束日期当天
    endDate.setHours(23, 59, 59, 999); // 设置为当天的最后一秒
    return { startDate, endDateNextDay };
  }
  const getMsgByDate = (key: string, date?: any): any[] => {
    const today = getCurrentDate();
    const tomorrow = new Date(today);
    if (key === '2') {
      // 今日
      tomorrow.setDate(today.getDate() + 1);
      const todayData = allMsg.value.filter((item) => {
        const requestDate = new Date(item.requestTime);
        requestDate.setHours(0, 0, 0, 0); // 忽略时间部分
        return requestDate >= today && requestDate < tomorrow;
      });
      return todayData;
    }
    if (key === '3') {
      // 近一周
      const oneWeekAgo = getDateNDaysAgo(7);
      const weekData = allMsg.value.filter((item) => {
        const requestDate = new Date(item.requestTime);
        requestDate.setHours(0, 0, 0, 0);
        return requestDate >= oneWeekAgo && requestDate < tomorrow;
      });
      return weekData;
    }
    if (key === '4') {
      // 近一月
      const oneMonthAgo = new Date(getCurrentDate());
      oneMonthAgo.setMonth(oneMonthAgo.getMonth() - 1);
      const monthData = allMsg.value.filter((item) => {
        const requestDate = new Date(item.requestTime);
        requestDate.setHours(0, 0, 0, 0);
        return requestDate >= oneMonthAgo && requestDate < tomorrow;
      });
      return monthData;
    }
    if (key === '5') {
      // 获取给定日期范围的数据
      if (date) {
        const startDateString = parseDateString(date[0]);
        const endDateString = parseDateString(date[1]);
        const { startDate, endDateNextDay } = getDateRange(startDateString, endDateString);
        const rangeData = allMsg.value.filter((item) => {
          const requestDate = new Date(item.requestTime);
          requestDate.setHours(0, 0, 0, 0);
          return requestDate >= startDate && requestDate < endDateNextDay;
        });
        return rangeData;
      }
    }
    return [];
  };
  const getAllMsg = async () => {
    // 获取发送人信息
    userId.value = userStore.userId;
    account.value = userStore.account;
    condition.value = `${account.value}(${userId.value})`;
    allMsg.value = [];
    if (account.value === '管理员') {
      await getMessageHistory(current.value, pageSize.value).then((res: any) => {
        total.value = res.data.total;
      });
      if (total.value !== 0) {
        const count = Math.ceil(total.value / 100);
        let data: any[] = [];
        for (let i = 0; i < count; i++) {
          await getMessageHistory(i + 1, pageSize.value).then((res: any) => {
            data = [...data, ...res.data.records];
          });
        }
        allMsg.value = data;
      }
    }
    else {
      await getMessageByPageAndName(current.value, pageSize.value, condition.value).then((res: any) => {
        total.value = res.data.total;
      });
      if (total.value !== 0) {
        const count = Math.ceil(total.value / 100);
        let data: any[] = [];
        for (let i = 0; i < count; i++) {
          await getMessageByPageAndName(i + 1, pageSize.value, condition.value).then((res: any) => {
            data = [...data, ...res.data.records];
          });
        }
        allMsg.value = data;
      }
    }
    getMsgByDate('2');
    getMsgByDate('3');
    getMsgByDate('4');
  };
  return {
    sum,
    successMsg,
    errorMsg,
    getAllMsg,
    getSumMsg,
    getMsgByDate,
  };
}, {
  persist: true,
});
